/*****************************************************************************
 * @brief TCP
 * @author Cokin
 *****************************************************************************/

/*****************************************************************************
 ! Import modules & config
 *****************************************************************************/
const server    = require('net').createServer()
const moment    = require('moment')

const app       = require('express')()
const http      = require('http').Server(app)
const io        = require('socket.io')(http)

const port = 8000
const webport = 8001

/*****************************************************************************
 ! vars
 *****************************************************************************/
let clientList = []         // device 客户列表
let webClientList = []      // web 客户列表
let devSocket

/*****************************************************************************
 ! Event
 *****************************************************************************/

/////////////////////////////////////////////////////////////////
// 连接成功，准备接收数据
server.on('connection', (socket) => {
    // 连接成功
    console.log('Server has a new device connection', socket.address())
    // 设置编码
    socket.setEncoding('utf8')
    // 长连接
    socket.setKeepAlive(true)

    // push list
    let name = socket.remoteAddress + ':' + socket.remotePort
    devSocket = socket
    console.log('Connected:',name)

    io.emit('DeviceDataReceived', '[' + moment().format('YYYY-MM-DD HH:mm:ss.SSS')  + '] ' + 'Device Connected: ' + name)

    // 接收数据
    socket.on('data', (data) => {
        // console.log('Received:',data)
        io.emit('DeviceDataReceived', '[' + moment().format('YYYY-MM-DD HH:mm:ss.SSS')  + '] ' + 'Server Received: ' + data)
    })

    // 断开连接
    socket.on('end', () => {
        io.emit('DeviceDataReceived', '[' + moment().format('YYYY-MM-DD HH:mm:ss.SSS')  + '] ' + 'Device Disconnected: ' + name)
        // console.log('Client connection ended')
    })
})

// 关闭连接
server.on('close', () => {
    console.log('Server is now closed')
})

// 错误
server.on('error', (err) => {
    console.log('Error occurred:', err.message)
})

/////////////////////////////////////////////////////////////////
// web
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html')
})

io.on('connection', function(socket){
    console.log('a user connected')

    socket.on('disconnect', function(){
        console.log('user disconnected')
    })

    socket.on('WebDataSend', function(msg){
        // console.log('Web Send: ' + msg)

        try {
            devSocket.write(msg)
        } 
        catch (e) {
            io.emit('DeviceDataReceived', '[' + moment().format('YYYY-MM-DD HH:mm:ss.SSS')  + '] ' + 'Server Reported Error: ' + e.message)
        }
        
    })
})



/*****************************************************************************
 ! Listening
 *****************************************************************************/
server.listen(port)

// 开始监听端口
server.on('listening', () => {
    console.log('Server is listening on port', port)
})

http.listen(webport, function(){
    console.log('websocket listening on *:' + webport)
})